<style>
</style>
<!--  -->
<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogFormVisible" @closed="closed" :close-on-click-modal="false">
      <el-form :model="page" v-loading="loading" :rules="rules" ref="pageForm" @submit.native.prevent>
        <el-form-item label="页面名称" label-width="120px" prop="name">
          <el-input v-model="page.name" autocomplete="off" size="medium" maxlength="50" style="width:80%;"
            placeholder="输入50个字符以内的页面名称"></el-input>
        </el-form-item>
        <el-form-item label="显示位置置于" label-width="120px">
          <el-select v-model="page.afterPageId" placeholder="请选择" size="medium" style="width:80%;">
            <template v-for="pag in pageList[0]">
              <el-option
                :key="pag.id" :label="pag.name" :value="pag.id"></el-option>
              <template v-for="pa in pageList[pag.id]">
                <el-option style="padding-left:36px;"
                  :key="pa.id" :label="' - '+pa.name" :value="pa.id"></el-option>
                <template v-for="pthree in pageList[pa.id]">
                  <el-option style="padding-left:48px;"
                    :key="pthree.id" :label="' -- '+pthree.name" :value="pthree.id"></el-option>
                </template>
              </template>
            </template>
          </el-select>
          <b class="blue">之后</b>
        </el-form-item>
        <el-form-item v-loading="loadingRewrite" label="自定义链接" label-width="120px"
          v-if="copyPageType === 1 || copyPageType === 2" prop="rewrite">
          <el-input v-model="page.rewrite" autocomplete="off" size="medium" maxlength="100" style="width:80%;"
            placeholder="输入非全数字、无空格特殊符号等且100个字符以内的字符串"></el-input>
          <p style="color:#888888;">路径：/{{page.rewrite? page.rewrite: '{系统默认ID}'}}.html</p>
        </el-form-item>
        <el-form-item label="外部链接" label-width="120px" v-if="copyPageType === 3" prop="url">
          <el-input v-model="page.url" autocomplete="off" size="medium" maxlength="200" style="width:80%;"
            placeholder="输入地址"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closed" size="small">取 消</el-button>
        <el-button type="primary" @click="onSubmit()" :disabled="loading || loadingRewrite" size="small">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as PubsubType from '@/config/pubsubtype.js'
import PubSub from 'pubsub-js'
export default {
  props: {
    propsOnSubmit: {
      type: Function
    }
  },
  created () {

  },
  data () {
    // 自定义校验
    var checkName = (rule, value, callback) => {
      if (value.trim() === '') {
        callback(new Error('页面名称不能都为空格'))
      } else {
        callback()
      }
    }
    var checkRewrite = (rule, value, callback) => {
      if (parseInt(this.page.type) === 3 || parseInt(this.page.type) === 4) {
        callback()
      }
      if (value) {
        if (/^\d+$/.test(value)) {
          callback(new Error('不能全部为数字'))
          return
        }
        if (!/([\u4e00-\u9fa5]|[a-zA-Z0-9])+/.test(value)) {
          callback(new Error('带有空格或特殊符号'))
          return
        }
        if (value.length < 3) {
          callback(new Error('不能小于3个字符'))
          return
        }
        if (/\s/.test(value)) {
          callback(new Error('带有空格'))
          return
        }
        let patrn = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")
        if (patrn.test(value)) {
          callback(new Error('带有特殊符号'))
          return
        }
        callback()
      } else {
        callback(new Error('不能为空'))
      }
    }
    return {
      dialogFormVisible: false,
      title: '',
      loading: true,
      loadingRewrite: false,
      isfromuser: false,
      page: {
        copyPageId: 0,
        name: '',
        afterPageId: 0,
        rewrite: '',
        url: '',
        toSiteId: -1
      },
      rules: {
        name: [
          { required: true, message: '请输入页面名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在1到50个字符', trigger: 'blur' },
          { validator: checkName, trigger: 'blur' }
        ],
        rewrite: [{ required: true, validator: checkRewrite, trigger: 'change' }]
      },
      // 是否加载完成
      bool: {
        pageList: false,
        systemList: false
      },
      // 当前系统当中已有的 page 数据
      pageList: [],
      // 当前系统当中已有的 system 数据
      systemList: [],
      // 是否显示错误
      internal: true,
      // 拷贝页面类型
      copyPageType: 1
    }
  },
  computed: {
    pageName () {
      return this.page.name
    }
  },
  watch: {
    pageName: {
      handler (newValue) {
        if (this.page.id > 0) {
          return
        }
        if (newValue) {
          let toLocaleLowerCase = this.$pinyin.getFullChars(newValue).toLocaleLowerCase()
          let rewrite = ''
          for (let i in toLocaleLowerCase) {
            let str = toLocaleLowerCase[i]
            if (/([\u4e00-\u9fa5]|[a-zA-Z0-9])/.test(str)) {
              rewrite += this.$pinyin.getFullChars(str).toLocaleLowerCase()
            }
          }
          if (rewrite.indexOf(this.page.rewrite) === 0) {
            this.page.rewrite = rewrite
          }
        } else {
          this.page.rewrite = this.page.rewrite
        }
      },
      deep: true
    },
    bool: {
      handler (newValue) {
        if (newValue.pageList) {
          this.loading = false
        } else {
          this.loading = true
        }
      },
      deep: true
    }
  },
  methods: {
    onSubmit () {
      if (this.loading) {
        return
      }
      this.$refs['pageForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          let sPageCopy = JSON.parse(JSON.stringify(this.page))
          // 请求写入数据库
          this.$jpost('/page/copy', sPageCopy).then(response => {
            this.loading = false
            if (response && response.id) {
              if (this.isfromuser) {
                this.propsOnSubmit()
              } else {
                // 刷新页面菜单数据
                PubSub.publish(PubsubType.PUBSUB_REFRENCE_NAVIGATION_INFO, () => {
                  this.dialogVisible = false
                  // 刷新页面部分的渲染
                  // PubSub.publish(PubsubType.PUBSUB_DESIGN_REFRESH_PAGE)
                })
                // 重新渲染页面的导航部分
                PubSub.publish(PubsubType.PUBSUB_RERENDER_NAVIGATION)
              }
              this.closed()
            }
          })
        } else {
          return false
        }
        if (this.$refs['pageForm']) {
          this.$refs['pageForm'].clearValidate()
        }
      })
    },
    show (id, type, name, isfromuser) {
      this.page.copyPageId = id
      this.title = '页面复制：' + name
      if (type) {
        this.copyPageType = type
      }
      if (isfromuser) {
        this.isfromuser = true
      }
      // 打开窗口
      this.dialogFormVisible = true
      // 加载 loading
      let bool = this.bool
      bool.systemList = false
      bool.pageList = false
      this.bool = JSON.parse(JSON.stringify(bool))
      // 获取页面数据
      this.$post('/page/infos').then(response => {
        if (response && response.pages) {
          this.pageList = response.pages
          this.page.afterPageId = this.pageList[0][0].id
        }
        let bool = this.bool
        bool.pageList = true
        this.bool = JSON.parse(JSON.stringify(bool))
      }, (error) => {
        console.error(error)
        let bool = this.bool
        bool.pageList = true
        this.bool = JSON.parse(JSON.stringify(bool))
      })
    },
    hidden () {
    },
    closed () {
      if (this.$refs['pageForm']) {
        this.$refs['pageForm'].clearValidate()
      }
      this.page = {
        copyPageId: 0,
        name: '',
        afterPageId: 0,
        rewrite: '',
        url: '',
        toSiteId: -1
      }
      this.title = ''
      this.isfromuser = false
      this.dialogFormVisible = false
    }
  }
}

</script>
